package com.ai.wxy.spring.auth.util;

import com.ai.wxy.spring.auth.dto.JwtUserDTO;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Clock;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.DefaultClock;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;


/**
 * JwtTokenUtil
 *
 * @author 石头
 * @Date 2019/10/30
 * @Version 1.0
 **/
@Getter
public class JwtTokenUtil {
    private static final String JWT_TOKEN_PREFIX = "Bearer ";
    private Clock clock = DefaultClock.INSTANCE;
    @Value("${jwt.secret:abc123}")
    private String secret;

    @Value("${jwt.expiration:60000}")
    private Long expiration;

    @Value("${jwt.header:token}")
    private String tokenHeader;
    @Value("${jwt.auth.passwd:false}")
    private Boolean pwdEncrpyt;
    @Value("${jwt.auth.path:/login}")
    private String loginPath;

    public static String getTokenPrefix(){
        return JWT_TOKEN_PREFIX;
    }
    public String getUsernameFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }

    public Date getIssuedAtDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getIssuedAt);
    }

    public Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }

    public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    private Claims getAllClaimsFromToken(String token) {
        return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
    }

    public Boolean validateToken(String token, JwtUserDTO userDetails) {
        final Date created = getIssuedAtDateFromToken(token);

        // 如果token存在没过期，且token创建日期 > 最后修改密码的日期 则代表token有效
        return (!isTokenExpired(token) && ! isCreatedBeforeLastPasswordReset(created, userDetails.getLastPasswordResetDate()));
    }

    private Boolean isTokenExpired(String token) {
        final Date expiration = getExpirationDateFromToken(token);
        return expiration.before(clock.now());
    }
    private Boolean isCreatedBeforeLastPasswordReset(Date created, Date lastPasswordReset) {
        return (lastPasswordReset != null && created.before(lastPasswordReset));
    }

    public String generateToken(UserDetails userDetails) {
        Map<String, Object> claims = new HashMap<>();
        return doGenerateToken(claims, userDetails.getUsername());
    }

    private String doGenerateToken(Map<String, Object> claims, String subject) {
        final Date createdDate = clock.now();
        final Date expirationDate = calculateExpirationDate(createdDate);

        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuedAt(createdDate)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    private Date calculateExpirationDate(Date createdDate) {
        return new Date(createdDate.getTime() + expiration);
    }
}
